﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DTO;
using System.Data.SqlClient;
using System.Data;
namespace DAO
{
    public class PhieuXuatKhoDAO
    {
        public List<PhieuXuatKhoDTO> LayDanhSachPhieuXuatKho()
        {
            List<PhieuXuatKhoDTO> listPXK = new List<PhieuXuatKhoDTO>();
            SqlConnection conn = null;
            SqlDataReader reader = null;
            try
            {
                String sql = "Select MaPhieuXK, NgayLap, xk.MaNV, TenNV, MaPYC from PhieuXuatKho xk, NhanVien nv where xk.MaNV = nv.MaNV";

                conn = DataProvider.ConnectDB();
                SqlCommand cm = new SqlCommand(sql, conn);
                reader = cm.ExecuteReader();
                while (reader.Read())
                {
                    PhieuXuatKhoDTO pxkDTO = new PhieuXuatKhoDTO();
                    pxkDTO.MaPhieuXK = reader.GetInt32(0);
                    pxkDTO.NgayLap = reader.GetDateTime(1);
                    pxkDTO.MaNV = reader.GetInt32(2);
                    pxkDTO.TenNV = reader.GetString(3);
                    pxkDTO.MaPYC = reader.GetInt32(4);
                    listPXK.Add(pxkDTO);
                }
            }
            catch (Exception ex)
            { String e = ex.ToString(); }
            finally
            { conn.Close(); }
            return listPXK;

        }
        public int ThemPhieuXuatKho(PhieuXuatKhoDTO pxkDTO)
        {
            int ID = -1;
            SqlConnection conn = null;
            try
            {
                conn = DataProvider.ConnectDB();
                String sql = "INSERT INTO PhieuXuatKho(NgayLap,MaNV,MaPYC)";
                sql += "VALUES(@NgayLap,@MaNV,@MaPYC)";
                SqlCommand cmd = conn.CreateCommand();
                cmd.CommandType = CommandType.Text;
                cmd.CommandText = sql;
                SqlParameter para;
                
                para = cmd.Parameters.Add("@NgayLap", SqlDbType.Date);
                para.Value = pxkDTO.NgayLap;
                para = cmd.Parameters.Add("@MaNV", SqlDbType.Int);
                para.Value = pxkDTO.MaNV;
                para = cmd.Parameters.Add("@MaPYC", SqlDbType.Int);
                para.Value = pxkDTO.MaPYC;

                cmd.ExecuteNonQuery();

                // lay id vua them

                sql = "Select @@IDENTITY";
                cmd = new SqlCommand(sql, conn);
                ID = Convert.ToInt32(cmd.ExecuteScalar());

            }
            catch (Exception ex)
            {
               
                
            }
            finally
            {
                conn.Close();
            }
            return ID;
        }
    }
}
